import React, { Component } from 'react';
import classnames from 'classnames';
import { toJS } from 'mobx';
import { inject, observer } from 'mobx-react';
import { Button, Radio, Checkbox, Spin, Tooltip } from 'antd';
import { WeaProgress, WeaAvatar, WeaAlertPage, WeaLocaleProvider, WeaPopoverHrm, WeaTools } from 'ecCom';
import VotePersonList from './VotePersonList';

const { viewer } = WeaTools;
const getLabel = WeaLocaleProvider.getLabel;

@inject('listStore')
@observer
export default class VoteDetails extends Component {
  constructor(props) {
    super(props);
    this.prefixCls = 'group-voting-list-detail';
    this.state = {
      value: 1,
      canVote: true,
    };
  }

  onChange = (e) => {
    this.setState({
      value: e.target.value,
    });
  };

  mutipleCheck = (e, id) => {
    const { listStore } = this.props;
    const { setStoreState, selectedKeys, dataInfo } = listStore;
    const check = e.target.checked;
    let tempArr = [];
    if (check && selectedKeys.indexOf(id) === -1) {
      tempArr = [...selectedKeys, id];
    } else if (!check && selectedKeys.indexOf(id) > -1) {
      tempArr = selectedKeys.filter(v => v !== id);
    }

    setStoreState({ selectedKeys: tempArr });

    if (dataInfo.maxvoteoption !== '0') {
      if (dataInfo.choosemodel === '1' && (Number(dataInfo.maxvoteoption) < tempArr.length)) {
        this.setState({ canVote: false });
      } else if (!this.state.canVote) {
          this.setState({ canVote: true });
        }
    }
  }

  renderOps = (data) => {
    const { listStore } = this.props;
    const { setStoreState, dataInfo } = listStore;
    if (data.votestatus === '0' && data.hasvote === '0') { // 进行中，个人未投票
      if (data.choosemodel === '1') { // 多选
        return (
          <div className={`${this.prefixCls}-options`}>
            {
              data.options && data.options.map(v => (
                  <div className={`${this.prefixCls}-options-line`}>
                    <Checkbox ecId={`${this && this.props && this.props.ecId || ''}_Checkbox@9gkxdd@${v.optionid}`} key={v.optionid} className={`${this.prefixCls}-options-line-checkbox`} onChange={e => this.mutipleCheck(e, v.optionid)}>
                      {v.optioncontent}
                    </Checkbox>
                    <div className={`${this.prefixCls}-options-line-imgs`}>
                      {
                        v.optionimg && v.optionimg !== '' && v.optionimg.split(',').map((img, index) => (
                          <img src={img} alt="" data-imgsrc={img} onClick={viewer} className="formImgPlay" />
                        ))
                      }
                    </div>
                  </div>
                ))
            }
          </div>
        );
      } else if (data.choosemodel === '0') { // 单选
        return (
          <div className={`${this.prefixCls}-options`}>
              {
                toJS(dataInfo) && toJS(dataInfo).options.map((v, index) => (
                    <div key={v.optionid} className={`${this.prefixCls}-options-line`}>
                      <Radio ecId={`${this && this.props && this.props.ecId || ''}_Radio@c4p56h@${v.optionid}`}
                        name="voteRadio"
                        checked={v.checked}
                        value={v.optionid}
                        className={`${this.prefixCls}-options-line-radio`}
                        onChange={(e) => {
                          const target = e.target;
                          if (target.checked) {
                            setStoreState({ selectedKeys: [target.value] });
                          }

                          let options = toJS(dataInfo).options;
                          options.map((item) => {
                            if (item.optionid === v.optionid) {
                              item.checked = target.checked;
                            } else {
                              item.checked = false;
                            }
                            return item;
                          });
                          setStoreState({
                            dataInfo: {
                              ...toJS(dataInfo),
                              options,
                            },
                          });
                        }}
                      >
                        {v.optioncontent}
                      </Radio>
                      <div className={`${this.prefixCls}-options-line-imgs`}>
                        {
                          v.optionimg && v.optionimg !== '' && v.optionimg.split(',').map((img, index) => (
                            <img src={img} alt="" data-imgsrc={img} onClick={viewer} className="formImgPlay" />
                          ))
                        }
                      </div>
                    </div>
                  ))
              }
          </div>
        );
      }
    } else if (data.votestatus === '1' || data.hasvote === '1') {
      return (<div className={`${this.prefixCls}-container-options`}>
        {
           data.options && data.options.map(v => (
              <div className={`${this.prefixCls}-container-optionItem`}>
                {
                  v.optionimg && v.optionimg !== '' && (
                    <div className={`${this.prefixCls}-options-line-imgs`}>
                      {
                        v.optionimg.split(',').map((img, index) => (
                          <img src={img} alt="" data-imgsrc={img} onClick={viewer} className="formImgPlay" />
                        ))
                      }
                    </div>
                  )
                }
                <div className="title">
                  <span className="content">
                    {v.voteThisOption == 1 && <i className="icon-coms-complete" style={{ color: '#008DFF' }} />}
                    {v.optioncontent}
                  </span>
                  <span
                    className="count"
                    style={(v.votecount * 1 > 0 && data.voteprivacy === '1') ? { cursor: 'pointer' } : {}}
                    onClick={() => {
                      if (v.votecount * 1 > 0 && data.voteprivacy === '1') {
                        this.viewPerson('2', v.optionid);
                      }
                    }}
                  >{v.votecount}{getLabel('18607', '票')}</span>
                </div>
                <WeaProgress ecId={`${this && this.props && this.props.ecId || ''}_WeaProgress@v5b8gk@${v.optionid}`} percent={Number(v.votepercent)} showInfo={false} strokeWidth={2} />
              </div>
            ))
        }
      </div>);
    }
  }

  renderPerson = (bool, label, person, data, params) => {
    if (bool) {
      if (data) {
        return (
          <div className={`${this.prefixCls}-peopleList`}>
            <div className={`${this.prefixCls}-peopleList-title`}>
              <span className="label">{label}</span>
              {
                (person && person.length > 0) && (
                  <span className="todetail" onClick={() => this.viewPerson(params)}>{getLabel('83110', '查看详情')} <i className="icon-coms-Right" /></span>
                )
              }
            </div>
            <div className={`${this.prefixCls}-peopleList-person`}>
              {
                (person && person.length > 0) && person.map(item => (
                  <div className={`${this.prefixCls}-peopleList-person-item`} key={item.voteuserid}>
                    <WeaAvatar ecId={`${this && this.props && this.props.ecId || ''}_WeaAvatar@s81wqb@${item.voteuserid}`} userId={item.voteuserid} url={item.messagerurl} name={item.voteusername} style={{ width: 34, height: 34 }} />
                    <Tooltip ecId={`${this && this.props && this.props.ecId || ''}_Tooltip@vwhb25@${item.voteuserid}`} title={item.voteusername} placement="rightBottom">
                      <div className={'name'} >{item.voteusername}</div>
                    </Tooltip>
                  </div>
                ))
              }
            </div>
          </div>
        );
      }
    }
  }

  onCancel = () => {
    const { listStore } = this.props;
    const { setStoreState, groupListStore } = listStore;
    setStoreState({ isShowDetail: false, dataInfo: {}, selectedKeys: [] });
    groupListStore.tableUpdate({ showCheck: true });
  }

  // 查看人员列表详情
  viewPerson = (usertype, optionid) => {
    const { listStore } = this.props;
    const { setStoreState, groupchatvoteprelist } = listStore;
    const personTitle = usertype === '1' ? getLabel('516178', '未投票人员') : getLabel('506561', '已投票人员');
    let params = { personVisible: true, usertype, personTitle };
    if (optionid) {
      params = { ...params, optionid };
    }
    setStoreState(params, groupchatvoteprelist);
  }

  render() {
    const { listStore } = this.props;
    const { isShowDetail, dataInfo, onVote, saveLoading, detailLoading, detailViewRight, selectedKeys } = listStore;
    const data = toJS(dataInfo);
    const detailCls = classnames({
      [this.prefixCls]: true,
      isShow: isShowDetail,
    });
    const votedCls = classnames({
      [`${this.prefixCls}-box`]: true,
      hasBtn: data.votestatus === '0' && data.hasvote === '0',
    });
    const optionText = data.maxvoteoption === '0' ? `(${getLabel('32499', '不限制')})` : <span style={!this.state.canVote ? { color: 'red' } : {}}>{`(${getLabel('516177', '最多可选')}${data.maxvoteoption}${getLabel('26302', '项')})`}</span>;
    if (detailLoading) {
      return (
        <div className={detailCls}>
          <Spin ecId={`${this && this.props && this.props.ecId || ''}_Spin@v8tps3`} />
        </div>
      );
    } else if (!detailViewRight) {
      return (
        <div className={detailCls}>
          <WeaAlertPage ecId={`${this && this.props && this.props.ecId || ''}_WeaAlertPage@0se4ch`}
            iconSize={100}
          >
            <div>{getLabel('516176', '投票不存在')}</div>
          </WeaAlertPage>
        </div>
      );
    }
    return (
      <div className={detailCls}>
        <div className={votedCls}>
          <div className={`${this.prefixCls}-header`}>
            <div className={`${this.prefixCls}-header-box`}>
              <div className={`${this.prefixCls}-header-theme`}>
                <span className="theme" dangerouslySetInnerHTML={{ __html: data.votetheme }} />
                {
                  data.votestatus === '0' ? <span className="group-voting-state-ing">{getLabel('1960', '进行中')}</span> :
                  <span className="group-voting-state-end">{getLabel('22348', '已结束')}</span>
                }
              </div>
              <div className={`${this.prefixCls}-header-info`}>
                <WeaPopoverHrm ecId={`${this && this.props && this.props.ecId || ''}_WeaPopoverHrm@t2xwk7`}>
                  <a href={`javaScript:openhrm(${data.createrid})`} className="creater" onClick={window.pointerXY} title={data.creatername}>{data.creatername}</a>
                </WeaPopoverHrm>
                <span className="time">{`${data.createdate} ${data.createtime}`}</span>
              </div>
            </div>
            <i className="icon-coms-Clear" onClick={this.onCancel} />
          </div>

          {
            data.themepicsrc !== '' && (
              <div className={`${this.prefixCls}-themeImg`}>
                <img alt="" src={data.themepicsrc || ''} data-imgsrc={data.themepicsrc} onClick={viewer} className="formImgPlay" />
              </div>
            )
          }

          <div className={`${this.prefixCls}-container`}>
            <div className={`${this.prefixCls}-container-title`}>
              <span>{data.choosemodelshow} {data.votestatus === '0' && data.choosemodel === '1' && optionText}</span>
              {(data.votestatus === '1' || data.hasvote === '1') && <span style={{ float: 'right' }}>{getLabel('500891', '已投')}{data.votetotalcount}{getLabel('18607', '票')}</span>}
            </div>
            { this.renderOps(data) }
            <div className={`${this.prefixCls}-container-endTime`}>
              <span>{`${getLabel('18111', '截止时间：')} ${data.enddate} ${data.endtime}`}</span>
              { data.showremindString && <span>{data.showremindString}</span> }
            </div>
          </div>

          { this.renderPerson(data.voteprivacy === '1', data.votelabel, data.havevotedpersons, data, '0') }
          { this.renderPerson(data.voteprivacy === '1', data.notvotelabel, data.havenotvotedpersons, data, '1') }
        </div>
        {
          data.votestatus === '0' && data.hasvote === '0' &&
          <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@ykkfo2`}
            type="primary"
            loading={saveLoading}
            className={`${this.prefixCls}-publish`}
            onClick={() => onVote()}
            disabled={toJS(selectedKeys).length === 0 || !this.state.canVote || saveLoading}
          >{getLabel('126097', '投票')}</Button>
        }
        <VotePersonList ecId={`${this && this.props && this.props.ecId || ''}_VotePersonList@47b4ei`} />
      </div>
    );
  }
}
